﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;

namespace Model.Managers
{
    public class UserDataManager
    {
        private Users _connectedUser;
        private IList<Contacts> _contactList;

        public UserDataManager(Users connectedUser)
        {
            _connectedUser = connectedUser;
            _contactList = GetAllContact();
        }

        public IList<Contacts> ContactList
        {
            get { return _contactList; }
            
        }

        public IList<Contacts> GetAllContact()
        {   
                var db = new AdressDBEntities();
                var contactList = (from c in db.Contacts
                                   where c.UserID == _connectedUser.UserID
                                   orderby c.ContactName, c.ContactFirstName
                                   select c).ToList();
                return contactList;
        }

        public void ModifyContact(Contacts contacttoModify)
        {
            var db = new AdressDBEntities();
            var contact = (from c in db.Contacts
                           where c.ContactID == contacttoModify.ContactID
                           select c).First();
            contact.ContactName = contacttoModify.ContactName;
            contact.ContactFirstName = contacttoModify.ContactFirstName;
            contact.ContactAdress = contacttoModify.ContactAdress;
            contact.ContactTel = contacttoModify.ContactTel;
            db.SaveChanges();
            _contactList = GetAllContact();
        }

        public void DeleteContact(Contacts contactToDelete)
        {
            var db = new AdressDBEntities();
            var contact = (from c in db.Contacts
                           where c.ContactID == contactToDelete.ContactID
                           select c).First();
            db.Contacts.DeleteObject(contact);
            db.SaveChanges();
            _contactList = GetAllContact();
        }

        public void AddContact(Contacts contactToAdd)
        {
            var db = new AdressDBEntities();
            var contact = Contacts.CreateContacts(-1, contactToAdd.ContactName, contactToAdd.ContactFirstName, _connectedUser.UserID, contactToAdd.ContactAdress, contactToAdd.ContactTel);
            db.Contacts.AddObject(contact);
            db.SaveChanges();
        }
    }
}
